package com.example.wanandroid.ui.fragment;

import static android.content.ContentValues.TAG;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.wanandroid.R;
import com.example.wanandroid.core.bean.BaseData;
import com.example.wanandroid.core.bean.BaseResponse;
import com.example.wanandroid.core.bean.project.ProjectListData;
import com.example.wanandroid.core.http.api.Apis;
import com.example.wanandroid.core.utils.HttpUtil;
import com.example.wanandroid.ui.adapter.ProjectListAdapter;
import com.scwang.smart.refresh.footer.BallPulseFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.SpinnerStyle;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ProjectItemListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ProjectItemListFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    int id;//项目页签分类id

    Apis api;
    volatile int page = 0;

    RecyclerView mRecyclerView;
//    MyAdapter mMyAdapter ;
    ProjectListData projectListData = new ProjectListData();

    RefreshLayout refreshLayout;

    ProjectListAdapter projectListAdapter;

    LinearLayoutManager linearLayoutManager;


    public ProjectItemListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FragmentProjectA.
     */
    // TODO: Rename and change types and number of parameters
    public static ProjectItemListFragment newInstance(String param1, String param2) {
        ProjectItemListFragment fragment = new ProjectItemListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.project_item_list_fragment, null);
        mRecyclerView = view.findViewById(R.id.project_list);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        projectListAdapter = new ProjectListAdapter(getActivity());
        mRecyclerView.setAdapter(projectListAdapter);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        id = getArguments().getInt("id");
        getProjectList();
        refreshLayout = view.findViewById(R.id.refresh_layout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
        refreshLayout.setRefreshFooter(new BallPulseFooter(getContext()).setSpinnerStyle(SpinnerStyle.Scale));
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            getProjectList();
            refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
        });
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {
            updateData();
            refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
        });
        return view;
    }

    private void getProjectList() {
        //通过simpleAdapter实现将网络请求来的数据绑定到view上，图片地址数据要做特殊处理

        //创建网络请求接口对象实例
        api = HttpUtil.getApi();
        //对发送请求进行封装，传入接口参数
        Call<BaseResponse<ProjectListData>> jsonData = api.getProjectListData(0,id);

        //发送网络请求(异步)
        jsonData.enqueue(new Callback<BaseResponse<ProjectListData>>() {
            @Override
            public void onResponse(Call<BaseResponse<ProjectListData>> call, Response<BaseResponse<ProjectListData>> response) {

                BaseResponse<ProjectListData> body = response.body();
                if(body==null) return;
                projectListData = body.getData();
                if(projectListData==null) return;

                ProjectListData listData = body.getData();
                List<BaseData> feedArticleDataList = new ArrayList<>(listData.getDatas());
                projectListAdapter.addDataList(feedArticleDataList);

            }

            @Override
            public void onFailure(Call<BaseResponse<ProjectListData>> call, Throwable t) {
                Log.e(TAG, "get回调失败：" + t.getMessage() + "," + t.toString());
            }
        });
    }

    private void updateData(){
        Call<BaseResponse<ProjectListData>> jsonData = api.getProjectListData(page,id);

        jsonData.enqueue(new Callback<BaseResponse<ProjectListData>>() {
            @Override
            public void onResponse(Call<BaseResponse<ProjectListData>> call, Response<BaseResponse<ProjectListData>> response) {

                BaseResponse<ProjectListData> body = response.body();
                if(body==null) return;
                projectListData = body.getData();
                if(projectListData==null) return;

                ProjectListData listData = body.getData();
                List<BaseData> feedArticleDataList = new ArrayList<>(listData.getDatas());
                projectListAdapter.addDataList(feedArticleDataList);

                page++;
            }

            @Override
            public void onFailure(Call<BaseResponse<ProjectListData>> call, Throwable t) {
                Log.e(TAG, "get回调失败：" + t.getMessage() + "," + t.toString());
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        refreshLayout = null;
        mRecyclerView = null;
        linearLayoutManager = null;
        projectListAdapter = null;
    }
}